package com.example.thread.async;

import com.example.base.Constants;
import com.example.mybatisplusstudy.mapper.BatchNoMapper;
import com.example.mybatisplusstudy.mapper.DataMapper;
import com.example.mybatisplusstudy.pojo.BatchNoDto;
import com.example.thread.LockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author code威
 * @version 1.0
 * @description: TODO
 * @date 2022/7/23 12:31
 */
@Service
@Slf4j
public class TestAsyncService {

    @Autowired
    private LockService lockService;

    @Autowired
    private DataMapper dataMapper;
    @Autowired
    private BatchNoMapper batchNoMapper;

    private static final String lockName = "testDataLock";

   @Async("myThreadPool")
    public void runTest() {

       String batchNo = "BUG01"+UUID.randomUUID().toString();
       MDC.put(Constants.REQ_ID,batchNo);
       log.info("开始记录,日志测试");
       try {
           while (true){
               boolean result = lockService.getLock(lockName,batchNo,"1");
               if(result){
                   log.info("完成数据处理开始,批次号为：{}",batchNo);
                   BatchNoDto batchNoDto = new BatchNoDto();
                   batchNoDto.setBatchNo(batchNo);
                   int i = dataMapper.updateData(batchNo);
                   lockService.updateLockStatus(lockName,batchNo,"0");

                   batchNoMapper.insert(batchNoDto);
                   log.info("完成数据处理结束,批次号为：{}",batchNo);

                   break;
               } else {
                   Thread.sleep(300);
               }
           }
       }catch (Exception e){
           log.info("异步更新批次号出现异常，e is :{}",e);
           lockService.updateLockStatus(lockName,batchNo,"0");

       }
       MDC.remove(Constants.REQ_ID);


    }


    @Async("myThreadPool")
    public void runTest01() {

        String batchNo = "TEST06"+UUID.randomUUID().toString();
        try {

            BatchNoDto batchNoDto = new BatchNoDto();
            batchNoDto.setBatchNo(batchNo);
            synchronized(lockName){
                log.info("完成数据处理开始,批次号为：{}",batchNo);
                int i = dataMapper.updateData(batchNo);
            }
            batchNoMapper.insert(batchNoDto);
            log.info("完成数据处理结束,批次号为：{}",batchNo);





        }catch (Exception e){
            log.info("异步更新批次号出现异常，e is :{}",e);
            lockService.updateLockStatus(lockName,batchNo,"0");

        }


    }
}
